import { ElMessage } from 'element-plus';

/**
 * 复制文本到剪贴板
 * @param {string} text 要复制的内容
 * @returns {Promise<void>} 复制成功 resolve，否则 reject
 */
export const copyTextToClipboard = (text) => {
	if (!text && text !== 0) {
		return ElMessage.warning('没有内容可复制');
	}
	if (navigator.clipboard && window.isSecureContext) {
		return navigator.clipboard.writeText(text);
	} else {
		const textarea = document.createElement('textarea');
		textarea.value = text;
		textarea.style.position = 'fixed';
		textarea.style.top = '-9999px';
		textarea.setAttribute('readonly', '');
		document.body.appendChild(textarea);
		textarea.select();
		try {
			document.execCommand('copy');
			document.body.removeChild(textarea);
			return ElMessage.success('复制成功');
		} catch (err) {
			document.body.removeChild(textarea);
			return ElMessage.error('复制失败');
		}
	}
};
